﻿#if UNITY_EDITOR

using System;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

public class NuGetTool
{
    private const string Config_File_Path = "Assets/Editor/NuGetSync.txt";

    private const string MenuItemPath_SyncExistDlls = "NuGet/Sync Dlls";

    [MenuItem(MenuItemPath_SyncExistDlls)]
    private static void MenuItem_SyncExistDlls()
    {
        if (!File.Exists(Config_File_Path))
        {
            Debug.LogWarning($"config file not exist: {Config_File_Path}");
            return;
        }

        using (var fs = new StreamReader(Config_File_Path, Encoding.UTF8))
        {
            var seperator = new string[] { ">>>" };
            string line = null;
            while (null != (line = fs.ReadLine()))
            {
                if (string.IsNullOrEmpty(line) || line.StartsWith("#")) continue;
                var splitArr = line.Split(seperator, StringSplitOptions.RemoveEmptyEntries);
                var srcDir = splitArr[0];
                var dstDir = splitArr[1];

                SyncDlls(line, srcDir.Trim(), dstDir.Trim());
            }
        }
        AssetDatabase.Refresh();
        Debug.Log("finish !!!");   
    }

    private static void SyncDlls(string line, string srcDir, string dstDir)
    {
        if (!dstDir.StartsWith("Assets", StringComparison.OrdinalIgnoreCase))
        {
            Debug.LogWarning($"dstDir: not in Assets/ folder, {line}");
            return;
        }
        if (!Directory.Exists(srcDir))
        {
            Debug.Log($"srcDir not exist: {line}");
            return;
        }
        if (!Directory.Exists(dstDir))
            Directory.CreateDirectory(dstDir);
        if (!Directory.Exists(dstDir))
        {
            Debug.LogError($"dstDir create fail: {dstDir}");
            return;
        }

        var filePaths = Directory.GetFiles(srcDir, "*.*", SearchOption.AllDirectories);
        foreach (var filePath in filePaths)
        {
            var dstFilePath = Path.Combine(dstDir, filePath);
            var parentDirPath = Path.GetDirectoryName(dstFilePath);
            if (!Directory.Exists(parentDirPath))
                Directory.CreateDirectory(parentDirPath);
            if (!Directory.Exists(parentDirPath))
            {
                Debug.LogError($"folder create fail: {parentDirPath}");
                continue;
            }

            bool isCopy = true;
            if (File.Exists(dstFilePath))
            {
                if (File.GetLastWriteTime(filePath) == File.GetLastWriteTime(dstFilePath))
                {
                    //Debug.Log($"no change: {dstFilePath}");
                    isCopy = false;
                }
                else
                {
                    File.Delete(dstFilePath);
                }
            }
            if (isCopy)
            {
                File.Copy(filePath, dstFilePath);
                Debug.Log($"updated: {dstFilePath}");
            }
        }
    }

}

#endif
